% Document.tex copyright 1992/3 Victor Eijkhout
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% D O C U M E N T   S T R U C T U R E %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\DefineTest:LocalReferences
\NewTrace:doc

% Start
% open external files and execute default commands
%
\newif\if@started
\def\Start{\@startedyes \the\start@commands
    \ifBasicIndentIsSet\else
       \Distance:basicindent=parindent \fi
    \set@level@indent}
\def\StartCommand#1{\adds@start@command{#1}}

% End 
% 1/ close any open groups and give warnings
% 2/ \vfil\eject the last page
% 3/ \immediate\close the .auxs file
% 4/ load the .aux for writing the external files
%    and testing changed references
%
\let\@end=\end 
\def\Stop{\Close@all@groups
    \the\stop@commands
    \vfil \penalty\slotpenalty 
    \ifnum\unknown@refs>\z@
      \message{-- There \ifnum\unknown@refs=\@ne was an \else
       were \number\unknown@refs\@space\fi
       unresolved reference\ifnum\unknown@refs>\@ne s\fi.}\fi
    \ifnum\duplicate@labels>\z@
      \message{-- There \ifnum\duplicate@labels=\@ne was an\else
       were \number\duplicate@labels\@space\fi
       duplicate label\ifnum\duplicate@labels>\@ne s\fi.}\fi
    \immediate@close@aux@file{aux}
    \ifWriteExtern \final@load@aux \fi
    \@end}
\def\StopCommand#1{\adds@stop@command{#1}}

%%%%%%%%%%%% input other files
\newwrite\aux@file \newwrite\incaux@file
\let\ifWriteaux\iftrue
\def\aux@name{aux} \def\aux@extension{aux}
\newif\if@auxopen \newif\if@incauxopen

% the following line is in output.tex
%\add@mark@item{first@page}

% Input files are in a group, 
% they also set the IsFirstPage test
\def\InputFile:#1 {\begingroup \def\input@name{#1}
    \Tmessage[doc]{Input File: #1}
    \refresh@mark@item{first@page}{yes}
    \refresh@mark@item{first@page}{no}
    \ifLocalReferences
          \get@aux@file{#1}{incaux}{aux}\fi
    \input@file{#1}%
    \immediate@close@aux@file{incaux}
    \Close@all@groups
    \def\test@input@name{#1}\ifx\input@name\test@input@name\else
        \Wmessage{Input `#1' overbalanced}\fi
    \endgroup}
\def\xInputFile:#1 {\input@file{#1}}
\def\input@file#1{\input #1 \vfil\penalty\slotpenalty\par}

\let\input@name=\@empty
\let\test@input@name=\@empty

% Input of Lollipop files
%
\def\InputLollipop:#1 {\makeatletter\input#1\relax\makeatother}

%%%%%%%%%%%%%%%% External Communication

% List of files
% not including the .aux file
%
\newtoks\ext@files@list \ext@files@list={}

% I don't want to remember my own naming conventions.
%
\def\file@ext@name#1{#1@extension}
\def\cs@file@ext@name#1{\csname#1@extension\endcsname}

% Define External File
% #1 is name known to style definition,
% #2#3#4 is three-letter file extension in
% file system
% 
% correspondence: \#1@extension = #2#3#4, \#2#3#4@name = #1
%
% user test \Write#1 to prevent overwriting
% internal test \if@#2#3#4open
% \newwrite\#2#3#4@file
%
\def\DefineExternalFile:#1=#2#3#4#5
   {\Tmessage[doc]{Define external file `#1' (ext=#2#3#4)}
    \csarg\newwrite{#2#3#4@file}
    \append@to@list{ext@files@list}{\\#2#3#4; }
    \csarg\newtoks{#1@local@defs}%constructed in \ExternalItem
    \csarg\gdef{\file@ext@name{#1}}{#2#3#4}
    \csarg\gdef{#2#3#4@name}{#1}
    \DefineTest:{Write#1}
    \global\csname Write#1yes\endcsname
    \csarg\newif{if@#2#3#4open}
   }

%%%% Load

% Initial load of the auxiliary file
%
\def\initial@load@aux{%\begingroup%why this group?
    \disable@external@write@command
    \Tmessage[doc]{Load initial aux file}
    \get@aux@file{\jobname}{aux}{aux}
    %\endgroup
    \ifWriteExtern 
        \open@ext@file@for@output{\jobname}{aux}{aux} 
    \fi}
% A test to determine all-or-nothing writing of .aux file.
% below there is a redefinition for bibTeX
\DefineTest:WriteExtern \WriteExtern:yes
\ifini{\add@start@command{\initial@load@aux}}

% Load of external file
%
\def\LoadExternalFile:#1
   {\if\UndefinedCS{\file@ext@name{#1}}
          \Wmessage{LoadExternalFile: unknown external file `#1'}
    \else \begingroup 
          \Tmessage[doc]{Loading external file: #1}
          \WriteExtern:no %prevent trouble with undefined entries
          \csarg\the{#1@local@defs}
          \get@aux@file{\jobname}{\cs@file@ext@name{#1}}
                       {\cs@file@ext@name{#1}}
          \endgroup
    \fi}

% Basic load
%
\def\get@aux@file#1#2#3{
    \csarg\openin{#2@file} #1.#3
    \csarg\ifeof{#2@file} 
          \message{No aux file `\csname#2@name\endcsname'}
       \else \csarg\closein{#2@file} 
          \Tmessage[ref]{Inputting aux file <#2>: <#1.#3>}
          \Tmessage[ext]{Inputting aux file <#2>: <#1.#3>}
          \makeatletter \input #1.#3 \makeatother
       \fi}

% Open for output:
% initially used for the .aux file
% at the final load of the .aux file used to generate .toc
% et cetera
%
\def\open@ext@file@for@output#1#2#3{
    \csname ifWrite\csname #2@name\endcsname\endcsname
        \immediate\openout\csname#2@file\endcsname=#1.#3
        \global\csname @#2openyes\endcsname
        \immediate\write\csname#2@file\endcsname{\relax}
        \Tmessage[doc]{File '#2' (#3) open for output}
        \Tmessage[ext]{File '#2' (#3) open for output}
    \else
        \global\csname @#2openno\endcsname
        \Tmessage[doc]{File '#2' (#3) not open for output}
        \Tmessage[ext]{File '#2' (#3) not open for output}
    \fi}
\def\open@external@files@for@output{
    \def\protect{\noexpand\protect\noexpand}
    \def\\##1;{##1}\Tmessage[doc]{External files: \the\ext@files@list}
    \def\\##1;{\open@ext@file@for@output{\jobname}{##1}{##1}}
    \the\ext@files@list}

\newif\iflabels@changed
\def\final@load@aux{\labels@changedno
    \def\refer@label##1##2##3{\test@refer@label{##1}{##2}{##3}}
    \open@external@files@for@output
    \install@external@write@command
    \Tmessage[doc]{Load aux for label testing and ext file generation}
    \Tmessage[ext]{Load aux for label testing and ext file generation}
    \makeatletter \input \jobname.aux 
    \end@write@extern
    \iflabels@changed \Wmessage{Labels have changed. Rerun!} \fi
    \makeatother}
\def\end@write@extern{
    \def\\##1;{\immediate@close@aux@file{##1}}
    \the\ext@files@list}
\def\close@aux@file  #1{\csname if@#1open\endcsname
    \write\csname#1@file\endcsname{\relax}
    \closeout\csname#1@file\endcsname 
    \Tmessage[doc]{File '#1' closed}\fi}
\def\immediate@close@aux@file#1{\csname if@#1open\endcsname
    \immediate\write\csname#1@file\endcsname{\relax}
    \immediate\closeout\csname#1@file\endcsname
    \Tmessage[doc]{File '#1' immediately closed}\fi}


% Generate the extern call in the style definition
% this one is part of 'external:<file name>'
%
\def\generate@extern#1{\edef\cs@e
   {\nxp\@add@toks{\nxp\@extern
             {\CSname{\file@ext@name{#1}}}
             {\@name}
             {\ifhas@counter \CSname{\@name Counter}\fi}
%\counter@@repr{\@name}
%{\nxp\the\counter@@name{\@name}}\fi}%
   }}\cs@e}

% call:
%  \@extern{extension}{object}{counter}\the\title@toks\e@extern
% to aux:
%  \write@to@external{extension}{object}{counter}{page}{tekst}\ew@extern
% to .extension file:
%  \object{counter}{page}tekst\par
% where \object is locally defined in the 'extension' file.
%
\def\ToExternalFile:#1=#2
 {\edef\cs@e{\nxp\x@extern{\cs@file@ext@name{#1}}}%
  \cs@e{anon}{}{#2}\e@extern}
\def\@extern#1{\ifWriteExtern
    \xp\x@extern \else \xp\skip@extern \fi {#1}}
\def\skip@extern#1#2#3\e@extern
    {\Tmessage[ext]{Skipped `#2' for `#1'}}
\newtoks\ext@text@toks
\newtoks\ext@labl@toks
\newtoks\ext@page@toks
\begingroup\noeol\catcode`\?\catcode`\%\catcode`\%=12
\gdef\x@extern#1#2#3#4#5\e@extern
 {\begingroup\normalesc
   \def\label[##1]{}
   \def\protect{\noexpand\protect\noexpand}
   \def\cprotect{\xp\string}
   \Tmessage[ext]{Write to aux `#2' for `\csname#1@name\endcsname'}
   \edef\cs@e{\write\aux@file{\string\write@to@external
          {#1}{#2}{#3}}}\cs@e
   \write\aux@file{
      {\counter@@repr{Page}{\csarg\number{\counter@name{Page}}}}%}
   \aux@write@external{#4}{#5}
   \write\aux@file{\string\ew@extern}
  \endgroup}
\normaleol\endgroup

% string a word, delimited by a space,
% first see whether it is a group, recognized by the fact
% that there is another space in it.
\def\string@um@up#1 {\string@space@group#1 \>\@bean}
\def\string@space@group#1 #2#3\@bean
   {\ifx#2\> \string@word#1\@roy
    \else \string{\string@um@up#1 #2#3 \string}%
    \fi \@space\string@um@up}
% a word is delimited by \@roy; if the word is \> then this
% is the last word, and we should remove 
% a trailing \@roy plus the \@space\string@um@up tokens after the call,
% but also parts of the conditional after the call have to be removed:
% \expandafter \take@three \expandafter \@roy \else .. \fi \@space\string@..
%
% sick. very sick.
%
\def\string@word#1{\ifx#1\>\xp\expandafter\xp\take@three\xp\expandafter
    \else \ifx#1\@roy
          \else \string#1\ifcat\nxp#1\relax\@space\fi
                \xp\xp\xp\string@word
    \fi   \fi}

% an attempt to string up a title. 
% this covers for the case where there are groups,
% but it is still quite wrong if \else or so is in the title
%
\NewDummy{@roy}\NewDummy{@bean}\NewDummy{@rope}\NewDummy{@bear}
\NewDummy{@Rope}
% Enable/Disable communication to external files
% former during initial load of .aux file,
% latter during final load of .aux file
%
\def\disable@external@write@command
   {\def\write@to@external##1\ew@extern{}}
\disable@external@write@command %do this initially just to be sure
\def\install@external@write@command %grouping ok?
   {\def\write@to@external##1##2##3##4##5\ew@extern
       {\csname if@##1open\endcsname 
            \Tmessage[ext]{Write `##2' 
                 to `\csname##1@name\endcsname'}
            \ext@labl@toks{##3}
            \ext@page@toks{##4}
            \ext@text@toks{##5}
            \immediate\write\csname##1@file\endcsname
                 {\CSname{##2}{\the\ext@labl@toks}%
                  {\the\ext@page@toks}\the\ext@text@toks
                  \string\par}
        \else
            \Tmessage[ext]{Skipped `##2' 
                 for `\csname##1@name\endcsname'}
        \fi}}

%%%%%%%%%%%%% BibTeX interface
% we interface ourselves to the BtxMac macros
% of Karl Berry and Oren Patashnik, version 0.99h

% prevent btxmac from rewriting *our* auxfile
% if btxmac has not been loaded this is just \relax
\adds@start@command{\csn @auxfiledonetrue\ecs}

% alternate name for the aux write stream
\adds@start@command{\let\@auxfile\aux@file}

% disable / alter Btxmac definitions
\def\bbl@hook{\default@everypar}
\adds@start@command{\let\bblhook\bbl@hook}

% switch off btxmac if need be
\xp\def\xp\WriteExternno\xp
  {\WriteExternno \let\noauxfile\@space}

% if you want to read an aux file but not load btxmac:
\let\bibstyle\take@one \let\bibdata\take@one
\let\citation\take@one \let\nocite\take@one
% similarly the source:
\let\bibliography\take@one \let\bibliographystyle\take@one

% user defined bibliography
\def\DefineBBL{\let\bbl@hook\BBL@hook \DefineList:BBL }
\def\BBL@hook
   {\def\begin##1##2{\default@everypar\BBL}\def\end##1{\>}%
        %intercept \begin{thebibliography}{width}
    \def\bibitem{\ifNextChar[%]
        \bbl@print@item\bbl@item}
    \def\biblabelprint##1{}
   }
\def\bbl@item#1{\item[#1]}
\def\bbl@print@item[#1]#2{\item<#1>[#2]}

% refer to a bib item
\def\bibref[#1]{\cite{#1}}%{[\ref[#1]]\nocite{#1}}

\def\one@bib@citation#1\@@{% this is what \bib@citation will become
   \if@notfirstcitation
      \printbetweencitations
   \fi
   %
   \expandafter \ifx \csname\@citelabel{#1}\endcsname \relax
      \if@citewarning
         \message{\@linenumber Undefined citation `#1'.}%
      \fi
      % Give it a dummy definition:
      \expandafter\gdef\csname\@citelabel{#1}\endcsname{%
         {\tt \nobreak\hskip0pt#1\nobreak\hskip0pt}}%
   \fi
   \@printlabel{#1}%
   \@notfirstcitationtrue
}
\def\@c@l#1{@empty}
\adds@start@command{\let\@onecitation\one@bib@citation
  \let\@citelabel\@c@l}

\endinput

92/11/18 \Start extended with start@commands and \basicindent
92/11/20 \StopCommand added
92/11/21 groups removed from initial loading aux (twice)
92/11/26 BibTeX interface
